﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace ArduinoInterOp.SystemCommands
{
    internal sealed class ArduinoListenerCommand : ArduinoCommand
    {
        private readonly List<byte> _pinsToListen;

        internal ArduinoListenerCommand(int intervalInMS)
        {
            IntervalInMs = intervalInMS;
            _pinsToListen = new List<byte>();
        }

        public int IntervalInMs { get; internal set; }

        internal void AddPinListener(byte pinNumber)
        {
            if(!_pinsToListen.Contains(pinNumber))
            {
                _pinsToListen.Add(pinNumber);
            }
        }

        internal void RemovePinListener(byte pinNumber)
        {
            if (_pinsToListen.Contains(pinNumber))
            {
                _pinsToListen.Remove(pinNumber);
            }
        }

        protected internal override void OnBeforeExecuting()
        { }

        protected override ArduinoCommandResult ProcessResult()
        {
            if (_pinsToListen.Count == 0)
            {
                return ArduinoCommandResult.Stopped;
            }

            this.Operations = _pinsToListen.Select(pin => new ArduinoPinOperationData(ArduinoCommands.GetPinValue, pin)).ToArray();
            this.StartTime = DateTime.Now.AddMilliseconds(IntervalInMs);

            return ArduinoCommandResult.Continue;
        }
    }
}
